import { Injectable, EventEmitter } from '@angular/core';
import { Http, URLSearchParams, Response, Headers } from '@angular/http';
import { getLocalItem, setLocalItem, removeItem } from 'utils';
import { HttpService } from 'service/HttpService';
import { Router } from '@angular/router';

@Injectable()
export class LoginService {

  emit: EventEmitter<boolean>;

  constructor(private http:Http,private httpService: HttpService, private router: Router) {
    this.emit = new EventEmitter();
  }

  loginIn(params) {
    const urlParams = new URLSearchParams();
    urlParams.append("grant_type", params.grant_type);
    urlParams.append("scope", params.scope);
    urlParams.append("username", params.username);
    urlParams.append("password", params.password);
    const headers = new Headers({
      'Content-Type': 'x-www-form-urlencoded'
    });

    let promise = new Promise((resolve, reject) => {
      this.http.post(`http://114.55.146.142:5000/token`, urlParams.toString(), headers).map(res => res.json()).subscribe(res => {
        if(res) {
          this.httpService.changeHeaders('Authorization', `${res.token_type} ${res.access_token}`);
          resolve(res);
        }
      }, (err) => {
        reject(err);
      });
    });

    return promise;
  }

  loginOut() {
    removeItem('auth');
    removeItem('userInfo');
    this.httpService.deleteHeaders('Authorization');
    this.router.navigate(['/index/login']);
  }
}
